package com.ad.platform.api;

import com.ad.payload.dto.LoginDto;
import com.ad.payload.enums.ResultCode;
import com.ad.payload.model.ResultBean;
import com.ad.payload.util.StringUtil;
import com.ad.payload.vo.LoginVo;
import com.ad.platform.common.constant.Const;
import com.ad.platform.common.constant.WxConst;
import com.ad.platform.common.enums.LoginTypeEnum;
import com.ad.platform.common.utils.FastJsonUtil;
import com.ad.platform.common.utils.RestTemplateUtil;
import com.ad.platform.service.IPfLoginService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author:dxgong
 * @日期 2021/3/21 15:45
 * @注释 登录
 */
@RestController
@RequestMapping("PfLoginApi")
@Slf4j
public class PfLoginApi {

    @Autowired
    private IPfLoginService insertWxUser;

    /**
     * 小程序登录
     * */
    @RequestMapping("/login")
    public ResultBean<LoginVo> login(@RequestBody @Valid LoginDto loginDto) {
        log.info("code: " + loginDto.getCode());
        if (StringUtil.isBlank(loginDto.getCode())) {
            return ResultBean.build(ResultCode.FAILED.getCode(), "登录code不能为空!");
        }
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        String url = WxConst.JS_CODE_2_SESSION + "appid=" + WxConst.appId + "&secret="
                + WxConst.appSecret + "&js_code=" + loginDto.getCode() + "&grant_type=authorization_code";
        String s = RestTemplateUtil.sendPostRequest(url, params, Const.GET_CODE);
        JSONObject jsonObjectToJsonStr = FastJsonUtil.getJsonObjectToJsonStr(s);

        String openId = jsonObjectToJsonStr.getString("openid");
        String sessionKey = jsonObjectToJsonStr.getString("session_key");
        String unionId = jsonObjectToJsonStr.getString("unionid");
        // 同步根据openid添加微信用户
        log.info("===== openId ===== : " + openId);
        log.info("===== session_key ===== : " + sessionKey);
        log.info("===== unionId ===== : " + unionId);

        loginDto.setOpenId(openId);
        loginDto.setSessionKey(sessionKey);
        loginDto.setUnionId(unionId);

        loginDto.setType(LoginTypeEnum.MINI_LOGIN.getCode());


        LoginVo loginVo = this.insertWxUser.insertWxUser(loginDto);

        log.info("===== loginVo ===== : " + loginVo);
        return ResultBean.success(loginVo);
    }


}
